<template>
  <div>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label for="exampleInputEmail1" class="form-label">邮箱地址</label>
        <validate-input
          :rules="emailRules"
          v-model="emailVal"
          placeholder="请输入邮箱地址"
          type="text"
          ref="inputRef"
        ></validate-input>
        <div class="form-text" v-if="emailRef.error">
          {{ emailRef.message }}
        </div>
      </div>
      <div class="mb-3">
        <label for="exampleInputPassword1" class="form-label">Password</label>
        <validate-input
          :rules="passwordRules"
          v-model="passwordVal"
          placeholder="请输入密码"
          type="password"
        ></validate-input>
      </div>
      <template #submit>
        <span class="btn btn-danger">登录</span>
      </template>
    </validate-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import {useStore} from 'vuex';
import ValidateInput, { RulesProp } from "../components/ValidateInput.vue";
import ValidateForm from "../components/ValidateForm.vue";
import createMessage from '../components/createMessage';
const emailReg = /^([a-zA-Z]|[0-9])(\w|)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
export default defineComponent({
  components: {
    ValidateInput,
    ValidateForm,
  },
  setup() {
    const router = useRouter();
    const store = useStore();
    const inputRef = ref<any>();

    const emailVal = ref("111@test.com");
    const emailRules: RulesProp = [
      { type: "require", message: "电子邮箱地址不能为空" },
      { type: "email", message: "请输入正确的电子邮箱格式" },
    ];

    const passwordVal = ref("111111");
    const passwordRules: RulesProp = [
      { type: "require", message: "密码不能为空" },
    ];

    const onFormSubmit = (result: boolean) => {
      if(result){
          const payload = {
            email:emailVal.value,
            password:passwordVal.value
          }
          store.dispatch('loginAndFetch',payload).then(data => {
            console.log(data);
            createMessage('登录成功 2秒后跳转首页','success');
            setTimeout(() => {
              router.push('/');
            },2000)
          }).catch(e => {
            console.log(e);
          })
          
      }
    };

    const emailRef = reactive({
      val: "",
      error: false,
      message: "",
    });

    const validataEmail = () => {
      if (emailRef.val.trim() === "") {
        emailRef.error = true;
        emailRef.message = "can not be empty";
      } else if (!emailReg.test(emailRef.val)) {
        emailRef.error = true;
        emailRef.message = "Should be vald emil";
      } else {
        emailRef.error = false;
      }
    };

    return {
      emailRef,
      validataEmail,
      emailRules,
      emailVal,
      passwordVal,
      passwordRules,
      onFormSubmit,
      inputRef,
    };
  },
});
</script>
